var async = require('async');
var helpers = require('../../../helpers/aws');

module.exports = {
    title: 'CloudTrail File Validation',
    category: 'CloudTrail',
    domain: 'Compliance',
    severity: 'Medium',
    description: 'Ensures CloudTrail file validation is enabled for all regions within an account',
    more_info: 'CloudTrail file validation is essentially a hash of the file which can be used to ensure its integrity in the case of an account compromise.',
    recommended_action: 'Enable CloudTrail file validation for all regions',
    link: 'http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-log-file-validation-enabling.html',
    apis: ['CloudTrail:describeTrails'],
    remediation_description: 'File validation will be enabled for the trail',
    remediation_min_version: '202010311808',
    apis_remediate: ['CloudTrail:describeTrails'],
    actions: {remediate: ['CloudTrail:updateTrail'], rollback: ['CloudTrail:updateTrail']},
    permissions: {remediate: ['cloudtrail:UpdateTrail'], rollback: ['cloudtrail:UpdateTrail']},
    realtime_triggers: ['cloudtrail:CreateTrail', 'cloudtrail:UpdateTrail','cloudtrail:DeleteTrail'],
    compliance: {
        hipaa: 'The auditing requirements of HIPAA require logs to be kept securely ' +
                'in a manner that prevents tampering. CloudTrail log validation ' +
                'provides a mechanism of validating that the logs generated by ' +
                'AWS have not been modified, ensuring the integrity of the log data.',
        cis2: '2.2 Ensure CloudTrail log file validation is enabled'
    },

    run: function(cache, settings, callback) {
        var results = [];
        var source = {};
        var regions = helpers.regions(settings);

        async.each(regions.cloudtrail, function(region, rcb){
            var describeTrails = helpers.addSource(cache, source,
                ['cloudtrail', 'describeTrails', region]);

            if (!describeTrails) return rcb();

            if (describeTrails.err || !describeTrails.data) {
                helpers.addResult(results, 3,
                    'Unable to query for CloudTrail file validation status: ' + helpers.addError(describeTrails), region);
                return rcb();
            }

            if (!describeTrails.data.length) {
                helpers.addResult(results, 2, 'CloudTrail is not enabled', region);
            } else if (describeTrails.data[0]) {
                for (var t in describeTrails.data) {
                    if (describeTrails.data[t].S3BucketName == helpers.CLOUDSPLOIT_EVENTS_BUCKET) continue;
                    if (!describeTrails.data[t].LogFileValidationEnabled) {
                        helpers.addResult(results, 2, 'CloudTrail log file validation is not enabled',
                            region, describeTrails.data[t].TrailARN);
                    } else {
                        helpers.addResult(results, 0, 'CloudTrail log file validation is enabled',
                            region, describeTrails.data[t].TrailARN);
                    }
                }
            } else {
                helpers.addResult(results, 2, 'CloudTrail is enabled but is not properly configured', region);
            }
            rcb();
        }, function(){
            callback(null, results, source);
        });
    },
    remediate: function(config, cache, settings, resource, callback) {
        var putCall = this.actions.remediate;
        var pluginName = 'cloudtrailFileValidation';
        var trailName;

        if (resource && resource.length) {
            trailName = resource.split('/')[1];
            config.region = resource.split(':')[3];
        } else {
            return callback('No resource to remediate');
        }

        var params = {
            'Name': trailName,
            'EnableLogFileValidation': true
        };


        var remediation_file = settings.remediation_file;
        remediation_file['pre_remediate']['actions'][pluginName][resource] = {
            'File Validation': 'Enabled',
            'Name': trailName
        };

        // passes the config, put call, and params to the remediate helper function
        helpers.remediatePlugin(config, putCall[0], params, function(err) {
            if (err) {
                remediation_file['remediate']['actions'][pluginName]['error'] = err;
                return callback(err, null);
            }

            let action = params;
            action.action = putCall;

            remediation_file['post_remediate']['actions'][pluginName][resource] = action;
            remediation_file['remediate']['actions'][pluginName][resource] = {
                'Action': 'ENABLED',
                'Name': trailName
            };
            settings.remediation_file = remediation_file;
            return callback(null, action);
        });
    }
};